import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:test0423/routes/routes.dart';
import 'package:video_player/video_player.dart';  // 添加视频播放器依赖
import '../models/post.dart';
import '../data/data_repository.dart';
import '../widgets/post_list_item.dart';

class PostListPage extends StatefulWidget {
  const PostListPage({Key? key}) : super(key: key);

  @override
  _PostListPageState createState() => _PostListPageState();
}

class _PostListPageState extends State<PostListPage> with TickerProviderStateMixin {
  late TabController _tabController;
  final List<Post> _posts = [];
  int _currentPage = 1;
  bool _isLoading = false;
  bool _hasMoreData = true;
  int _currentTab = 0;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
    _tabController.addListener(_onTabChanged);
    _loadPosts();
  }

  void _onTabChanged() {
    if (_tabController.index != _currentTab) {
      setState(() {
        _currentTab = _tabController.index;
        _posts.clear();
        _currentPage = 1;
        _hasMoreData = true;
      });
      _loadPosts();
    }
  }

  Future<void> _loadPosts() async {
    if (_isLoading || !_hasMoreData) return;

    setState(() => _isLoading = true);
    try {
      final newPosts = await DataRepository.fetchPosts(page: _currentPage, tab: _currentTab);
      setState(() {
        if (newPosts.isEmpty) {
          _hasMoreData = false;
        } else {
          _posts.addAll(newPosts);
          _currentPage++;
        }
        _isLoading = false;
      });
    } catch (e) {
      setState(() => _isLoading = false);
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Failed to load posts: $e')),
      );
    }
  }

  @override
  void dispose() {
    _tabController.removeListener(_onTabChanged);
    _tabController.dispose();
    super.dispose();
  }

  Widget _buildImageGrid(List<String> images) {
    return GridView.count(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      crossAxisCount: 3, // Display images in a 3-column grid
      mainAxisSpacing: 4.0,
      crossAxisSpacing: 4.0,
      children: images.map((imageUrl) {
        return GestureDetector(
          onTap: () {
            // Open full-screen image viewer
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => FullScreenImageViewer(
                  images: images,
                  initialIndex: images.indexOf(imageUrl),
                ),
              ),
            );
          },
          child: Image.network(
            imageUrl,
            fit: BoxFit.cover,
            errorBuilder: (context, error, stackTrace) {
              return Container(
                color: const Color(0xFFFFD7C5),
                child: const Center(
                  child: Icon(
                    Icons.image_not_supported,
                    color: Color(0xFFFF5A33),
                  ),
                ),
              );
            },
            loadingBuilder: (context, child, loadingProgress) {
              if (loadingProgress == null) return child;
              return Container(
                color: const Color(0xFFFFD7C5),
                child: const Center(
                  child: CircularProgressIndicator(
                    color: Color(0xFFFF5A33),
                  ),
                ),
              );
            },
          ),
        );
      }).toList(),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: TabBar(
          controller: _tabController,
          tabs: const [
            Tab(text: "关注"),
            Tab(text: "发现"),
          ],
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: [
          _buildPostList(),
          const Center(child: Text("发现页面内容")),
        ],
      ),
    );
  }

  Widget _buildPostList() {
    return ListView.builder(
      itemCount: _posts.length + (_isLoading ? 1 : 0) + (!_hasMoreData && _posts.isNotEmpty ? 1 : 0),
      itemBuilder: (context, index) {
        if (index == _posts.length) {
          if (!_hasMoreData) {
            return const Center(child: Text("No more data"));
          }
          return const Center(child: CircularProgressIndicator());
        }
        return PostListItem(post: _posts[index]);
      },
    );
  }
}

// 全屏图片查看器
class FullScreenImageViewer extends StatefulWidget {
  final List<String> images;
  final int initialIndex;

  const FullScreenImageViewer({Key? key, required this.images, required this.initialIndex}) : super(key: key);

  @override
  _FullScreenImageViewerState createState() => _FullScreenImageViewerState();
}

class _FullScreenImageViewerState extends State<FullScreenImageViewer> {
  late PageController _pageController;

  @override
  void initState() {
    super.initState();
    _pageController = PageController(initialPage: widget.initialIndex);
  }

  @override
  void dispose() {
    _pageController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: Stack(
        children: [
          PageView.builder(
            controller: _pageController,
            itemCount: widget.images.length,
            itemBuilder: (context, index) {
              return Center(child: Image.network(widget.images[index], fit: BoxFit.contain));
            },
          ),
          Positioned(
            top: 40,
            right: 20,
            child: IconButton(
              icon: const Icon(Icons.close, color: Colors.white),
              onPressed: () => Navigator.pop(context),
            ),
          ),
        ],
      ),
    );
  }
}

// 添加视频播放组件
class VideoPlayerWidget extends StatefulWidget {
  final String videoUrl;
  
  const VideoPlayerWidget({Key? key, required this.videoUrl}) : super(key: key);
  
  @override
  _VideoPlayerWidgetState createState() => _VideoPlayerWidgetState();
}

class _VideoPlayerWidgetState extends State<VideoPlayerWidget> {
  late VideoPlayerController _controller;
  bool _isPlaying = false;
  bool _isInitialized = false;
  bool _isFullScreen = false;
  
  @override
  void initState() {
    super.initState();
    _initializeController();
  }
  
  Future<void> _initializeController() async {
    _controller = VideoPlayerController.network(widget.videoUrl);
    try {
      await _controller.initialize();
      setState(() {
        _isInitialized = true;
      });
    } catch (e) {
      print('视频初始化错误: $e');
    }
  }
  
  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }
  
  void _togglePlay() {
    setState(() {
      _isPlaying = !_isPlaying;
      _isPlaying ? _controller.play() : _controller.pause();
    });
  }
  
  void _toggleFullScreen() {
    if (_isFullScreen) {
      Navigator.pop(context);
    } else {
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => Scaffold(
            backgroundColor: Colors.black,
            body: SafeArea(
              child: Stack(
                children: [
                  Center(
                    child: AspectRatio(
                      aspectRatio: _controller.value.aspectRatio,
                      child: VideoPlayer(_controller),
                    ),
                  ),
                  Positioned(
                    top: 16,
                    left: 16,
                    child: IconButton(
                      icon: const Icon(Icons.arrow_back, color: Colors.white),
                      onPressed: () => Navigator.pop(context),
                    ),
                  ),
                  Center(
                    child: IconButton(
                      icon: Icon(
                        _isPlaying ? Icons.pause_circle_filled : Icons.play_circle_fill,
                        size: 64,
                        color: Colors.white.withOpacity(0.7),
                      ),
                      onPressed: _togglePlay,
                    ),
                  ),
                  Positioned(
                    bottom: 16,
                    left: 16,
                    right: 16,
                    child: VideoProgressIndicator(
                      _controller,
                      allowScrubbing: true,
                      colors: const VideoProgressColors(
                        playedColor: Color(0xFFFF5A33),
                        bufferedColor: Colors.white30,
                        backgroundColor: Colors.white10,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      );
    }
  }
  
  @override
  Widget build(BuildContext context) {
    if (!_isInitialized) {
      return Container(
        height: 200,
        color: Colors.black,
        child: const Center(
          child: CircularProgressIndicator(
            color: Color(0xFFFF5A33),
          ),
        ),
      );
    }
    
    return Container(
      height: 200,
      color: Colors.black,
      child: Stack(
        alignment: Alignment.center,
        children: [
          // 视频播放器
          GestureDetector(
            onTap: _togglePlay,
            child: AspectRatio(
              aspectRatio: _controller.value.aspectRatio,
              child: VideoPlayer(_controller),
            ),
          ),
          
          // 播放/暂停按钮
          if (!_isPlaying)
            IconButton(
              icon: const Icon(
                Icons.play_circle_fill,
                size: 64,
                color: Colors.white,
              ),
              onPressed: _togglePlay,
            ),
          
          // 全屏按钮
          Positioned(
            bottom: 8,
            right: 8,
            child: IconButton(
              icon: const Icon(
                Icons.fullscreen,
                color: Colors.white,
              ),
              onPressed: _toggleFullScreen,
            ),
          ),
          
          // 进度条
          Positioned(
            bottom: 0,
            left: 0,
            right: 0,
            child: VideoProgressIndicator(
              _controller,
              allowScrubbing: true,
              colors: const VideoProgressColors(
                playedColor: Color(0xFFFF5A33),
                bufferedColor: Colors.white30,
                backgroundColor: Colors.white10,
              ),
            ),
          ),
        ],
      ),
    );
  }
}
